<?php

namespace catchAdmin\phone\model;

use catchAdmin\model\Notice;
use catchAdmin\model\UserCompanyStatusLog;
use catchAdmin\model\WechatUser;
use catcher\exceptions\AlertErrorException;

class UserExt extends \catchAdmin\model\UserExt
{

    public function saveData($param)
    {
        if (!empty((new \catchAdmin\model\UserCompany())
            ->where('wechat_user_id', $this->getLoginId())
            ->where('company_status', "<>", 4)
            ->count())) {
            throw new AlertErrorException('已提交公司认证，不能重复提交');
        }

        $this->startTrans();

        // 1.保存
        $user_ext_msg = $this->saveDataApp($param);

        // 2.记录日志
        (new UserCompanyStatusLog())->saveDataCC([
            'wechat_user_id' => $user_ext_msg['wechat_user_id'],
            'user_ext_id'    => $user_ext_msg['id'],
            'status_no'      => $user_ext_msg['status_no'],
            'company_status' => $user_ext_msg['company_status'],
        ]);

        // 3.更新用户表
        (new WechatUser())->saveDataCC([
            'id'             => $user_ext_msg['wechat_user_id'],
            'parent_id'      => $user_ext_msg['parent_id'],
            'company_type'   => $user_ext_msg['company_type'],
            'company_status' => $user_ext_msg['company_status'],
        ]);

        // 4.发消息
        (new Notice())->saveDataCC([
            // 个人认证——待审核
            'notice_type'    => 4,
            'title'          => '待审核',
            'content'        => "等待后台审核",
            'wechat_user_id' => $user_ext_msg['wechat_user_id'],
        ]);

        $this->commit();

        return $user_ext_msg;
    }


    ######################################## 显示 ################################################

    public function readData($param)
    {
        $wechat_user_id = $param['wechat_user_id'] ?? 0;
        if (empty($wechat_user_id)) {
            $wechat_user_id = $this->getLoginId();
        }

        $msg = $this
            ->where("wechat_user_id", $wechat_user_id)
            ->find();

        if (empty($msg)) {
            return [];
        }

        return $msg;
    }

}
